package com.sita.cfmoto.ui.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.sita.cfmoto.R;
import com.sita.cfmoto.TabController;
import com.sita.cfmoto.drivedata.DriveDataMainFragment;
import com.sita.cfmoto.event.HasBindVehicleEvent;
import com.sita.cfmoto.event.LogoutEvent;
import com.sita.cfmoto.interact.activity.ReleaseActiveActivity;
import com.sita.cfmoto.interact.activity.ReleaseDynamicActivity;
import com.sita.cfmoto.interact.fragment.InteractFragment;
import com.sita.cfmoto.login.LoginActivity;
import com.sita.cfmoto.my.MyProfileFragment;
import com.sita.cfmoto.my.activity.BindVehicleActivity;
import com.sita.cfmoto.my.activity.NoticeActivity;
import com.sita.cfmoto.persistence.User;
import com.sita.cfmoto.rest.model.BindedVehicle;
import com.sita.cfmoto.rest.model.Inform;
import com.sita.cfmoto.services.XmppBackgroundService;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.ui.fragments.HomeFragment;
import com.sita.cfmoto.ui.view.ImgTextBtn;
import com.sita.cfmoto.utils.InteractUtils;
import com.sita.cfmoto.utils.LocalStorage;
import com.sita.cfmoto.utils.LogUtils;
import com.sita.cfmoto.utils.PersistUtils;
import com.sita.cfmoto.utils.SessionUtils;
import com.sita.cfmoto.utils.VehicleUtils;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushManager;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class MainActivity extends ActivityBase {
    protected static final String TAG = MainActivity.class.getSimpleName();
    private static Boolean isQuit = false;

    @Bind(R.id.release_txt)
    TextView release;
    @Bind(R.id.notice_img)
    ImageView notice;
    @Bind(R.id.notice_badge_img)
    ImageView noticeBadge;
    private User mUser;
    private ServiceConnection connection;
    private Boolean hasBindVehicle = false;
    private boolean isFirstGet = true;
    private Toast toast;

    private TabController mTabController;
    private int mCurrIndex;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isQuit = false;
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hasBindVehicle();
        SessionUtils.login();
        setContentView(R.layout.activity_main_home);
        ButterKnife.bind(this);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initTab();
        initHuanXin();
        mUser = PersistUtils.getCurrentUser();
        easeComLogin();
        toast = Toast.makeText(this, R.string.again_to_exit_app, Toast.LENGTH_SHORT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    }

    protected void exitAppComplete() {
        doStopService();
        super.exitAppComplete();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        hasBindVehicle();
        mTabController.showTab(mCurrIndex);
        if (mCurrIndex == 3)
            refreshNoticeBadge();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (toast != null) {
            toast.cancel();
        }
    }
    private void initHuanXin() {
//        // 0.注册数据更新监听器
//        updateListViewReceiver = new MsgReceiver();
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction("com.qq.xgdemo.activity.UPDATE_LISTVIEW");
//        registerReceiver(updateListViewReceiver, intentFilter);

        // 注册接口
        XGPushManager.registerPush(getApplicationContext(), String.valueOf(LocalStorage.getAccountId()),
                new XGIOperateCallback() {
                    @Override
                    public void onSuccess(Object data, int flag) {
                        Log.w(com.tencent.android.tpush.common.Constants.LogTag,
                                "+++ register push sucess. token:" + data);
                    }

                    @Override
                    public void onFail(Object data, int errCode, String msg) {
                        Log.w(com.tencent.android.tpush.common.Constants.LogTag,
                                "+++ register push fail. token:" + data
                                        + ", errCode:" + errCode + ",msg:"
                                        + msg);
                    }
                });

        // 开启logcat输出，方便debug，发布时请关闭
// XGPushConfig.enableDebug(this, true);
// 如果需要知道注册是否成功，请使用registerPush(getApplicationContext(), XGIOperateCallback)带callback版本
// 如果需要绑定账号，请使用registerPush(getApplicationContext(),account)版本
// 具体可参考详细的开发指南
// 传递的参数为ApplicationContext
        Context context = getApplicationContext();
        XGPushManager.registerPush(context);

//// 2.36（不包括）之前的版本需要调用以下2行代码
//        Intent service = new Intent(context, XGPushService.class);
//        context.startService(service);


// 其它常用的API：
// 绑定账号（别名）注册：registerPush(context,account)或registerPush(context,account, XGIOperateCallback)，其中account为APP账号，可以为任意字符串（qq、openid或任意第三方），业务方一定要注意终端与后台保持一致。
// 取消绑定账号（别名）：registerPush(context,"*")，即account="*"为取消绑定，解绑后，该针对该账号的推送将失效
// 反注册（不再接收消息）：unregisterPush(context)
// 设置标签：setTag(context, tagName)
// 删除标签：deleteTag(context, tagName)

    }
    public void onEvent(LogoutEvent event) {
        SessionUtils.logout();
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isQuit) {
                isQuit = true;
//                Toast.makeText(getApplicationContext(), R.string.again_to_exit_app,
//                        Toast.LENGTH_SHORT).show();
//                toastText.setText("再按一次退出程序");
                toast.show();
//                ToastUtils.show(MainActivity.this, R.string.again_to_exit_app, Toast.LENGTH_SHORT);
                // 利用handler延迟发送更改状态信息
                mHandler.sendEmptyMessageDelayed(0, 1000);
            } else {
                finish();
//                exitAppComplete();
            }
        }
        return false;
    }


    private void initTab() {
        ImgTextBtn[] mButtons = new ImgTextBtn[4];
        mButtons[0] = (ImgTextBtn) findViewById(R.id.btn_home);
        mButtons[1] = (ImgTextBtn) findViewById(R.id.btn_travel);
        mButtons[2] = (ImgTextBtn) findViewById(R.id.btn_interact);
        mButtons[3] = (ImgTextBtn) findViewById(R.id.btn_mine);

        Fragment[] fragments = new Fragment[4];
        fragments[0] = new HomeFragment();
        fragments[1] = new DriveDataMainFragment();
        fragments[2] = new InteractFragment();
        fragments[3] = new MyProfileFragment();
        mTabController = new TabController(mButtons, fragments, getSupportFragmentManager(), R.id.main_home_fragment_container);
        mTabController.registerListener(new TabController.OnTabSelectedListener() {
            @Override
            public void onSelected(int index) {
                mCurrIndex = index;
                switch (index) {
                    case 0:
                        release.setVisibility(View.INVISIBLE);
                        notice.setVisibility(View.INVISIBLE);
                        noticeBadge.setVisibility(View.INVISIBLE);
                        break;
                    case 1:
                        release.setVisibility(View.INVISIBLE);
                        notice.setVisibility(View.INVISIBLE);
                        noticeBadge.setVisibility(View.INVISIBLE);
                        break;
                    case 2:
                        release.setVisibility(View.VISIBLE);
                        notice.setVisibility(View.INVISIBLE);
                        noticeBadge.setVisibility(View.INVISIBLE);
                        break;
                    case 3:
                        release.setVisibility(View.INVISIBLE);
                        notice.setVisibility(View.VISIBLE);
                        noticeBadge.setVisibility(View.INVISIBLE);
                        // refresh notice number badge;
                        refreshNoticeBadge();
                        break;
                    default:
                        break;
                }
            }
        });
        mTabController.showTab(mCurrIndex);
    }

    private void refreshNoticeBadge() {
        noticeBadge.setVisibility(View.INVISIBLE);
        Log.d("通知", "refresh");
        InteractUtils.fetchInform(1, 0, new InteractUtils.FetchInformListCallback() {
            @Override
            public void onInformListFetched(List<Inform> informList) {
                if (informList != null && !informList.isEmpty()) {
                    long lastRefreshNotificationTime = LocalStorage.getLastNotificationTimeStamp();
                    if (informList.get(0).doTime > lastRefreshNotificationTime) {
                        // has new notification
                        new Handler().post(new Runnable() {
                            @Override
                            public void run() {
                                noticeBadge.setVisibility(View.VISIBLE);
                            }
                        });
                    }
                }
            }
        });


    }

    private void doStartXmppService() {
        Intent intent = new Intent(getApplicationContext(), XmppBackgroundService.class);

        Log.d(TAG, "xmpp account is " + mUser.getXmppUser() + "/" + mUser.getXmppPass());

        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.d("LOG", "Activity ->Connected the Service");
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.d("LOG", "Activity ->Disconnected the LocalService");
            }
        };

        getApplication().startService(intent);
        bindService(intent, connection, BIND_AUTO_CREATE);
        Log.d(TAG, "XmppService is started and binded to TinterestActivity");
    }

    private void doStopService() {
        if (connection != null) {
            unbindService(connection);
            connection = null;
        }
        Intent intent = new Intent(getApplicationContext(), XmppBackgroundService.class);
        getApplication().stopService(intent);
        Log.d(TAG, "Xmpp Service is stopped and unbind");
    }

    @OnClick(R.id.release_txt)
    void onClickRelease(View view) {
        showPopupMenu(view);
    }

    @OnClick(R.id.notice_img)
    void onClickNotice() {
        Intent intent = new Intent();
        intent.setClass(this, NoticeActivity.class);
        startActivity(intent);
    }

    private void showPopupMenu(View view) {
        // View当前PopupMenu显示的相对View的位置
        PopupMenu popupMenu = new PopupMenu(this, view);
        popupMenu.getMenuInflater().inflate(R.menu.menu_release, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
//                Toast.makeText(GlobalContext.getGlobalContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
                switch (item.getItemId()) {
                    case R.id.action_release_dynamic:
                        Intent dynamicIntent = new Intent();
                        dynamicIntent.setClass(GlobalContext.getGlobalContext(), ReleaseDynamicActivity.class);
                        startActivity(dynamicIntent);
                        return true;
                    case R.id.action_release_active:
                        Intent activeIntent = new Intent();
                        activeIntent.setClass(GlobalContext.getGlobalContext(), ReleaseActiveActivity.class);
                        startActivity(activeIntent);
                        return true;
                }
                return false;
            }
        });
        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
            }
        });
        popupMenu.show();
    }


    private void easeComLogin() {
        EMClient.getInstance().login(
                mUser.getXmppUser(),
                mUser.getXmppPass(),
                new EMCallBack() {

                    @Override
                    public void onSuccess() {
                        LogUtils.d(TAG, "easecom login ok");
//                            // 登陆成功，保存用户名
////                            FriendHelper.getInstance().setCurrentUserName(person.getXmppUser());
//                            // 注册群组和联系人监听
//                            FriendHelper.getInstance().registerGroupAndContactListener();


                        // TODO: 2015/12/14 update nickname

                        // TODO: 2015/12/14 update header

                    }

                    @Override
                    public void onError(int i, String s) {
                        LogUtils.d(TAG, "easecom login error:" + s);
                    }

                    @Override
                    public void onProgress(int i, String s) {
                        LogUtils.d(TAG, "easecom login on progress" + i + s);
                    }
                }
        );
    }

    private void openBindVehicleDialog() {
        final NormalDialog dialog = new NormalDialog(MainActivity.this);
        dialog.style(NormalDialog.STYLE_TWO)
                .titleTextSize(20)
                .titleTextColor(getResources().getColor(R.color.black))
                .title("提示")
                .contentTextColor(getResources().getColor(R.color.black))
                .contentGravity(Gravity.CENTER)
                .content("还未绑定车辆")
                .contentTextSize(16)
                .btnText("暂时不绑定", "进入绑定界面")
                .btnTextColor(getResources().getColor(R.color.common_text))
                .btnTextSize(20)
                .cornerRadius(10)
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                }, new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        // right
                        dialog.dismiss();
                        Intent intent = new Intent();
                        intent.setClass(MainActivity.this, BindVehicleActivity.class);
                        startActivity(intent);
                    }
                });
    }

    private void hasBindVehicle() {
        VehicleUtils.fetchBindedVehicles(new VehicleUtils.FetchBindedVehiclesCallback() {
            @Override
            public void onBindedVehiclesFetched(List<BindedVehicle> vehicles) {
                if (vehicles == null || vehicles.isEmpty()) {
                    hasBindVehicle = false;
                    LocalStorage.setCurrSelectedVehicle("");
                } else if (vehicles != null && !vehicles.isEmpty() && vehicles.size() >= 1) {
                    if (LocalStorage.getCurrSelectedVehicle() == null || LocalStorage.getCurrSelectedVehicle().isEmpty()) {
                        BindedVehicle vehicle = vehicles.get(0);
                        VehicleUtils.setCurrentSelectedVehicle(vehicle.vin);
                    }
                    hasBindVehicle = true;
                } else {
                    hasBindVehicle = false;
                    LocalStorage.setCurrSelectedVehicle("");
                }

                if (isFirstGet && !hasBindVehicle) {
                    openBindVehicleDialog();
                    isFirstGet = false;
                }
                LocalStorage.setHasBindVehicle(hasBindVehicle);
                EventBus.getDefault().post(new HasBindVehicleEvent(hasBindVehicle));
            }
        });
    }


}